<template>
    <div class="wfull">
        <template v-if="showFile">
            <template v-if="multiple">
                <div class="wfull flex" v-for="(item, index) in fileValue" :key="index">
                    <p class="flex-1 overflow"> {{item}} </p>
                    <i @click="deleteFile(index)" class="fs14 icon-close color-red pointer"></i>
                </div>
            </template>
            <template v-else>
                <div class="wfull flex" v-if="fileValue">
                    <p class="flex-1 overflow mar-r5" style="direction: rtl"> {{fileValue}} </p>
                    <i @click="deleteFile" class="fs14 icon-close color-red pointer"></i>
                </div>
            </template>
        </template>
        <Upload
            v-if="(!multiple && !fileValue) || (multiple && fileValue.length < limit)"
            class="up-load"
            v-model:file-list="tempFileList"
            name="file"
            :max-count="1"
            :data="{
                fileType: 'excelDir',
                fileName: 'file',//Math.random().toString(32).slice(2),
                token: $store.state.user.account.token
            }"

            :action="uploadApi"
            :before-upload="beforeUpload"
            @change="handleChange"
        >
            <span class="upload_span pointer" style="color: #4d84fd">点击上传</span>
        </Upload>
    </div>
</template>

<script lang="jsx" setup>
    import { ref, onMounted, watch, inject } from 'vue'
    import { Upload } from 'ant-design-vue';
    import apiList from '@/api/apiList'
    import Loading from "@/components/baseUI/Loading";
    import { uploadFile, baiduDiyIocr, getKtIocrResult } from '@/api/base'
    import { useStore } from 'vuex';
import { progressStatuses } from 'ant-design-vue/es/progress/props';
    const Store = useStore()
    const uploadApi = ref( apiList.baseUrl + apiList.base.uploadFile )
    const editerMainBillInfoProvide = inject('editerMainBillInfoProvide')

    const props = defineProps({
        value: {
            type: [String, Array],
            default: ''
        },
        showFile: {
            type: Boolean,
            default: true
        },
        multiple: {
            type: Boolean,
            default: false
        },
        limit: {
            type: Number,
            default: 1
        },
        fieldData: {
            type: Object,
            default: () => ({})
        },
        lineItem: { //整行的数据(或者主表的数据列表)
            type: [Object, Array],
            default: () => ({})
        },

    })
    const emit = defineEmits([ 'update:value', 'success' ])
    watch(() => props.value, (val) => {
        fileValue.value = val
    })
    onMounted(() => {
        fileValue.value = props.value
    })


    function beforeUpload(e) {
        return new Promise((resolve, reject) => {
            /**
             * 识别配置方法
             * 1、在字段配置中 文件类型中选择 file(文件上传) "文件识别类型" 选择一个识别类型，例如百度
             * 2、"文件识别类型" 子二个字段 配置识别模板字段，没有的话可以不选，模板字段需要在表里配置一个字段，
             *    模板字段可以手填，也可以有选项中带出来。选项中带出来的用 SQL-LOOKUP 选项值中多返回一个 F开头的 配置的模板字段
             * 3、根据模板识别内容配置 "文件识别字段" ，根据配置内容回填到主表中
             * */
            console.log(props.fieldData);
            console.log(e);
            console.log(props.lineItem);
            if(props.fieldData.FFileSbType) {
                let type = props?.fieldData?.FFileSbType?.split(',')[0] || ''
                let tempIdField = props?.fieldData?.FFileSbType?.split(',')[1]
                let FFileSbField = props?.fieldData?.FFileSbField
                let sbMap = {}
                if(FFileSbField) {
                    let FFileSbFieldList = JSON.parse(FFileSbField) || []
                    FFileSbFieldList.forEach(item => {
                        sbMap[item.sbField] = {
                            fields: item.billField,
                            billType: item.type
                        }
                    })
                }

                console.log(sbMap);

                // let tempId = ''
                // if(tempIdField) {
                //     let tempIdName = ''
                //     if(Array.isArray(props.lineItem)) {
                //         props.lineItem.forEach(item => {
                //             if( item.FFieldName == tempIdField) {
                //                 tempId = item.value
                //                 tempIdName = item.FFieldTitle
                //             }
                //         })
                //     } else {
                //         Object.keys(props.lineItem).forEach(field => {
                //             if(tempIdField == field) {
                //                 tempId = props.lineItem[field].value
                //                 tempIdName = props.lineItem[field].FFieldTitle
                //             }
                //         })

                //     }
                //     console.log(tempId, 'tempId');
                //     if(!tempId) {
                //         $global.message.error('没有“' + tempIdName + '”字段')
                //         setTimeout(Loading.hide, 20)
                //         return reject()
                //     }
                // }

                // 百度保单
                if(type == 'bdbd') {
                    let upData = new FormData()
                    upData.append('token', Store.state.user.account.token)
                    upData.append('bookNo', Store.state.user.account.bookNo)
                    // upData.append('bdTemplateId', tempId)
                    upData.append('file', e)
                    upData.append('fileName', 'file')

                    // baiduDiyIocr(upData, {
                    getKtIocrResult(upData, {
                        loadingText: '保单识别中...',
                    }).then(res => {
                        // res = {
                        //     "code": 1,
                        //     "msg": "操作成功",
                        //     "data": {
                        //         "车架号": "LBELFAFC0HY084351",
                        //         "保险人": "李莉云",
                        //         "联系手机": "159****1667",
                        //         "开始时间": "2024-06-17 00:00:00",
                        //         "车型": "北京现代BH7162RAV轿车",
                        //         "保费": "1638.97",
                        //         "起止时间": "2024年06月17日00:00:00至2025年06月16日24:00:00",
                        //         "保单号": "1375405282024001662",
                        //         "车牌号": "闽DM6G70",
                        //         "结束时间": "2025-06-16 24:00:00"
                        //     }
                        // }
                        resolve()
                        let resData = res.data
                        let resList = Object.keys(resData).map(key => ({
                            key,
                            val: resData[key]
                        }))

                        console.log(resList, 'resList');

                        let dataList = resList.filter(i => sbMap[i.key])
                        dataList.forEach(item => {
                            console.log(item.val);
                            if(item.key.indexOf('起止时间') > -1) {
                                if (item.val.indexOf('年') > -1 && item.val.indexOf('月') > -1 && item.val.indexOf('日') > -1) {
                                    let dayList = [];
                                    let dayReg = /(\d+)[年月日]/ig
                                    var regRes;
                                    while (regRes = dayReg.exec(item.val)) {
                                        dayList.push({
                                            dateNum: regRes[1],
                                            dateStr: regRes[0]
                                        })
                                    }
                                    let unPass = false
                                    dayList.forEach((dItem, dIdx) => {
                                        if(dIdx == 0 || dIdx == 3) {
                                            dItem.dateNum = '20' + (('00' + dItem.dateNum).slice(-2))
                                        } else if(dIdx == 1 || dIdx == 4) {
                                            dItem.dateNum = ('0' + dItem.dateNum).slice(-2)
                                            if(+dItem.dateNum > 12) unPass = true;
                                        } else if(dIdx == 2 || dIdx == 5) {
                                            dItem.dateNum = ('0' + dItem.dateNum).slice(-2)
                                            if(+dItem.dateNum > 31) unPass = true;
                                        }
                                    })
                                    if(unPass) {
                                        item.val = ''
                                    } else {
                                        if(dayList.length == 3) {
                                            item.val = dayList.slice(3).map(i => i.dateNum).join('-')
                                        } else if(dayList.length == 6) {
                                            item.val = [
                                                dayList.slice(0, 3).map(i => i.dateNum).join('-'),
                                                dayList.slice(3, 6).map(i => i.dateNum).join('-'),
                                            ]
                                        } else {
                                            item.val = ''
                                        }
                                    }
                                    console.log(item.val, 'ddddd');
                                }
                            } else if(item.key.indexOf('时间') > -1) {

                            } else if(item.key.indexOf('保费') > -1) {
                                let numReg = /[0-9]+(\.\d+)?/ig
                                item.val = item.val.replace(',', '')
                                item.val = item.val.replace('，', '')
                                let numRes = numReg.exec(item.val)
                                if(numRes) {
                                    item.val = numRes[0]
                                } else {
                                    item.val = ''
                                }
                            }


                            const formatVal = (val, fieldItem) => {
                                if(val && fieldItem.FValSource == 'date') {
                                    return val.dateFormat(fieldItem.FValScope)
                                } else {
                                    return val
                                }
                            }


                            // item.val 可能是 字符串，[字符]， [字符，字符]
                            // sbMap[item.key].fields  配置的表字段，用来回填用的
                            // sbMap[item.key].type main 是主表，其他就是当前表
                            console.log(sbMap);
                            console.log(editerMainBillInfoProvide.value);
                            console.log(props.lineItem);

                            sbMap[item.key].fields.forEach((field, index) => {
                                console.log(field, sbMap[item.key].billType);
                                if(sbMap[item.key].billType == 'main') {
                                    let formIndex = editerMainBillInfoProvide.value.findIndex( fieldItem => field == fieldItem.FFieldName)
                                    console.log(formIndex);
                                    console.log( editerMainBillInfoProvide.value[formIndex] )
                                    if(!editerMainBillInfoProvide.value[formIndex].value) {
                                        if(Array.isArray(item.val)) {
                                            editerMainBillInfoProvide.value[formIndex].value = formatVal(item.val[index], editerMainBillInfoProvide.value[formIndex])
                                        } else {
                                            editerMainBillInfoProvide.value[formIndex].value = formatVal(item.val, editerMainBillInfoProvide.value[formIndex])
                                        }
                                    }
                                } else {
                                    if(Array.isArray(props.lineItem)) {
                                        let formIndex = props.lineItem.findIndex( fieldItem => field == fieldItem.FFieldName)
                                        let _val = Array.isArray(item.val) ? formatVal(item.val[index], props.lineItem[formIndex]) : formatVal(item.val, props.lineItem[formIndex])
                                        props.lineItem[formIndex].value = _val
                                    } else {
                                        let _val = Array.isArray(item.val) ? formatVal(item.val[index], props.lineItem[field]) : formatVal(item.val, props.lineItem[field])
                                        props.lineItem[field].value = _val
                                    }
                                }
                            })
                        })
                    })
                } else {
                    resolve()
                }
            } else {
                resolve()
            }
        })
    }

    const tempFileList = ref([])
    const fileValue = ref('')

    function handleChange(e) {
        if(e.file.status == 'done') {
            Loading.hide()
            let res = e.file.response
            if(res.code == 1) {
                if(props.multiple) {
                    fileValue.value.push(res.data.url)
                } else {
                    fileValue.value = res.data.url
                }
                emit('update:value', fileValue.value)
                emit('success', fileValue.value)
            } else {
                $global.message.error(res.msg)
                tempFileList.value = []
            }
        } else {
            Loading.show()
        }
    }
    function deleteFile(index) {
        tempFileList.value = []
        if(props.multiple) {
            fileValue.value.splice(index , 1)
            emit('update:value', fileValue.value)
        } else {
            fileValue.value = ''
            emit('update:value', '')
        }
    }
</script>

<style lang="less" scoped>
.up-load{
    :deep(.ant-upload-list){
        display: none;
    }
}

</style>
